from paho.mqtt import client as mqtt_client


# 创建连接到目标mqtt服务器的mqtt客户端
def connect_mqtt(serverIP='192.168.1.166', serverPort=8311, clientId=f'python-mqtt-001'):
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    newClient = mqtt_client.Client(clientId)
    newClient.on_connect = on_connect
    newClient.connect(serverIP, serverPort)
    return newClient


# 通过客户端将消息发布到mqtt服务器
def publish(publishClient, msgTopic="连接测试", msg="连接测试数据"):
    result = publishClient.publish(msgTopic, msg)
    # result: [0, 1]
    status = result[0]
    if status == 0:
        print(f"Send `{msg}` to topic `{msgTopic}`")
    else:
        print(f"Failed to send message to topic {msgTopic}")

# # 3.1 将密文通过mqtt发送给省厅
# # 要发布到mqtt服务器上的消息
# reportText = '{\n"appId":"1660567817461248002",\n"extend1":"",\n"extend2":"",\n"data":' + str(
#     encipheredText) + '\n}'
# print(reportText)
#
# # 目标mqtt服务器的ip地址、端口
# broker = Configurations.objectiveIP
# port = int(Configurations.mqttPort)
# # 发布的消息所属的topic，订阅了同样topic的其他用户客户端可以收到我们发布的这条消息
# topic = "1660567817461248002"
# # 此客户端的id，可完全自定义
# clientId = f'Baosight-DMZMqtt-007'
#
# # 发布
# client = connect_mqtt(broker, port, clientId)
# client.loop_start()
# publish(client, topic, reportText)
